/*
 * @Author: hx 2542123711@QQ.com
 * @Date: 2024-12-11 20:05:38
 * @LastEditors: hx 2542123711@QQ.com
 * @LastEditTime: 2024-12-15 16:58:32
 * @FilePath: /class_thread/thread-cp/mycp.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <unistd.h>
#include "blockqueue.hpp"
#include "task.hpp"
#include <ctime>

using namespace std;

void *Consumer(void *args)
{
    // blockqueue<int>* bq = static_cast<blockqueue<int>*>(args);
    blockqueue<Task> *bq = static_cast<blockqueue<Task> *>(args);

    while (true)
    {
        // 保证让生产者先生产
        usleep(10);
        // int a = bq->pop();
        // cout <<"Consumer: " << a << endl;
        Task t = bq->pop();
        t.run();

        cout << "Consumer: " << t.ConsumerShow() << endl;
        sleep(1);//生产和消费者模型是同步操作的
    }
}

void *Productor(void *args)
{
    srand(time(nullptr));

    // blockqueue<int>* bq = static_cast<blockqueue<int>*>(args);
    blockqueue<Task> *bq = static_cast<blockqueue<Task> *>(args);

    // int data =0;

    while (true)
    {
        char operation[5] = "+-*/";
        int data1 = rand() % 10;
        usleep(10);
        int data2 = rand() % 10;
        int op = operation[rand() % 4];

        Task t(data1, data2, op);
        // bq->push(data);
        bq->push(t);
        // cout <<"Productor: " << data++ << endl;
        cout << "Productor: " << t.ProductorShow() << endl;
    }
}

int main()
{
    pthread_t c, p;

    // blockqueue<int>* bq = new blockqueue<int>(4);
    blockqueue<Task> *bq = new blockqueue<Task>();

    pthread_create(&c, nullptr, Consumer, bq);
    pthread_create(&p, nullptr, Productor, bq);

    sleep(1);

    pthread_join(c, nullptr);
    pthread_join(p, nullptr);

    delete bq;

    return 0;
}